/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.predictors;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class MovingAverageThread extends PredictorThread {
	private List<Double> lastChanges = new LinkedList<Double>();
	private double lastAverageOfAverages = 0.0;
	private double lastChange = 0.0;
	private boolean dirty = false;

	public MovingAverageThread(long oldTime, long predictionTime, int noPoints,
			long sleepTime,String qosName,  Map<String, String> parameterMap) {
		super(oldTime, predictionTime, noPoints, sleepTime, qosName, parameterMap);
	}

	@Override
	public double predictedChange(long time) {
		double retval = 0;
		double[] temp = this.differenceOfLoads();
		for (int i = 0; i < temp.length; i++) {
			retval += temp[i];
		}
		return -(((retval / temp.length) * (time / 1000.0)) / 10.0);
	}

	@Override
	protected void calculate() {
		double averages[] = new double[counts.length - 5];
		double avgLength = 5;
		for (int i = 1; i < noPoints - avgLength - 1; i++) {
			double sum = 0.0;
			for (int j = 0; j < avgLength; j++) {
				sum += counts[i + j];
			}
			averages[i] = sum / avgLength;
		}
		double sumOfDifferences = 0.0;
		for (int i = 0; i < averages.length; i++) {
			sumOfDifferences += averages[i];
		}
		this.currentLoad = sumOfDifferences / averages.length;
		double sumOfSlope = 0.0;
		for (int i = 2; i < averages.length; i++) {
			// System.out.println("\t" + (averages[i] - averages[i - 1]));
			sumOfSlope += averages[i - 1] - averages[i];
		}
		this.slope = sumOfSlope / (averages.length - 1.0);
		this.addLoad(currentLoad);
	}

	@Override
	public double currentLoad() {
		return currentLoad;
	}

	@Override
	public double currentSlope() {
		return slope;
	}
}
